#define _GNU_SOURCE
#include <dirent.h>     /* Defines DT_* constants */
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <sys/syscall.h>
#include "autoComplete.h"
#include <string.h>
#define handle_error(msg) \
               do { perror(msg); exit(EXIT_FAILURE); } while (0)


struct linux_dirent {
   	   long           d_ino;
           off_t          d_off;
           unsigned short d_reclen;
           char           d_name[];
};

#define BUF_SIZE 1024


struct _DIRECTORY_LIST * getDirFileList(char *dir) {
	int fd, nread;
	int bpos;
	char buf[BUF_SIZE];
	struct linux_dirent *d;
	char **list;
	int i, count;
	struct _DIRECTORY_LIST *dirList;

	dirList = (struct _DIRECTORY_LIST *)malloc(sizeof(struct _DIRECTORY_LIST));


	fd = open(dir,O_RDONLY);
	if(fd == -1) {
		return NULL;
	}

	count = countFiles(dir);
	list = (char **)malloc((count+2)*sizeof(char *));
	for(i=0;i<count;i++) {
		list[i] = (char *)malloc(255*sizeof(char));
	}

	i = 0;
	while(1) {
		nread = syscall(SYS_getdents,fd,buf,BUF_SIZE);
		
		if(nread == -1) {
			return NULL;
		}

		if(nread == 0) {
			break;
		}

		for(bpos = 0; bpos < nread;) {
			d = (struct linux_dirent *) (buf+bpos);
			strcpy(list[i++],d->d_name);
			bpos += d->d_reclen;	
		}
	}
	list[i] = NULL;	
	
	dirList->list = list;
	dirList->size = count;
	return dirList;
}

int countFiles(char *dir) {

	int file_count = 0;
	DIR * dirp;
	struct dirent * entry;

	dirp = opendir(dir); /* There should be error handling after this */
	while ((entry = readdir(dirp)) != NULL) {
         	file_count++;
	}
	closedir(dirp);

	return file_count;
}

struct _DIRECTORY_SEARCH_INDEX * search(struct _DIRECTORY_LIST *dir, char *s) {
	int i,j;
	int str_size;
		
	struct _DIRECTORY_SEARCH_INDEX *sdir;

	sdir = (struct _DIRECTORY_SEARCH_INDEX *)malloc(sizeof(struct _DIRECTORY_SEARCH_INDEX));
	sdir->v = (int *)malloc(sizeof(int)*dir->size);
	sdir->size= 0;

	str_size = strlen(s);
	j = 0;
	i = 0;
	while(dir->list[i] != NULL) {
		if(strncmp(dir->list[i],s,str_size) == 0) {
			sdir->v[j++] = i;
			(sdir->size)++;
		}
		i++;
	}
	
	return sdir;

}
